class Maintenance < ActiveRecord::Base
  belongs_to :work
  belongs_to :team
  belongs_to :train_task
  belongs_to :worker
  has_many   :checkrecords
  has_one    :train, :through => :train_task
  

  #根据train_task_id来查找记录，并且进行分页
  def self.findPageByTrainTaskId(offset, limit ,train_task_id)
    find(:all,
      :offset     => offset,
      :limit      => limit,
      :conditions => ['train_task_id = ?',train_task_id],
      :order      => 'begin_time')
  end

  #根据train_task_id来查找记录
  def self.findByTrainTaskId(train_task_id)
    find(:all,
      :conditions => ['train_task_id = :train_task_id', {:train_task_id => train_task_id}],
      :order      => 'begin_time')
  end

  def self.findByTeamAndTime(team_id,time,errortime)
    time1 = time-(60*errortime.to_i)
    time2 = time+(60*errortime.to_i)
    find(
      :first,
      :conditions => ['team_id = ? AND begin_time >= ? AND begin_time <= ?',team_id,time1,time2]
    )
  end

  def self.findByTeamAndFlag(team_id,flag)
    find(
      :all,
      :conditions => ["team_id = ? AND flag = ?",team_id,flag]
    )
  end

  #根据train_task_id来数记录
  def self.countByTrainTaskId(train_task_id)
    count(:conditions => ['train_task_id = ?',train_task_id])
  end

  def self.findByTeamAndTrainTask teamId,deviceId
    find(
      :first,
      :conditions => ['team_id = ? AND train_task_id in (select id from train_tasks where is_end in (2,3) and device_id = ?)',teamId,deviceId],
      :order => 'created_at DESC'
    )
  end
  
end
